package com.glela.sensitiveWords.util;

import com.glela.common.util.Config;
import com.glela.sensitiveWords.beans.Node;

import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

/**
 * 文件下载工具类
 * Created by liujie
 */
public class HttpDownloadUtils {

    public static Node downloadAndParseSensitiveWordsFile() throws Exception {
        // 下载网络文件
        int bytesum = 0;
        int byteread = 0;
        InputStream inStream = null;
        FileOutputStream fs = null;
        try {
            URL url = new URL(Config.getString("sensitiveWords_file_net_path"));
            URLConnection conn = url.openConnection();
            inStream = conn.getInputStream();
            fs = new FileOutputStream("sensitive-words.txt");

            byte[] buffer = new byte[1024];
            while ((byteread = inStream.read(buffer)) != -1) {
                bytesum += byteread;
                fs.write(buffer, 0, byteread);
            }
        } catch (Exception e) {
            throw new Exception("敏感词文件下载解析错误", e);
        } finally {
            try {
                if (inStream != null) {
                    inStream.close();
                }
                if (fs != null) {
                    fs.close();
                }
            } catch (Exception e) {
                throw new Exception("敏感词文件关闭错误", e);
            }
        }
        SensitiveWordsFilterUtils.parseFile("sensitive-words.txt");
        return SensitiveWordsFilterUtils.tree;
    }
}
